﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelUtilities.Data;

namespace ExcelUtilities
{
    /// <summary>
    /// 验证器
    /// </summary>
    internal class Validator
    {
        string cellAddress, rule, errorMessage;
        CellValue value;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="cellAddress">单元格地址（如A1）</param>
        /// <param name="value">单元格数据值</param>
        /// <param name="rule">验证规则</param>
        /// <param name="errorMessage">验证不通过的异常信息</param>
        public Validator(string cellAddress, CellValue value, string rule, string errorMessage = null)
        {
            this.cellAddress = cellAddress;
            this.value = value;
            this.rule = rule;
            this.errorMessage = errorMessage;
        }

        /// <summary>
        /// 执行验证 返回验证不通过提示信息
        /// 如果验证通过则返回string.Empty
        /// </summary>
        /// <returns></returns>
        public string Execute()
        {
            string errMsg = string.Empty;
            if (string.IsNullOrEmpty(rule))
                return string.Empty;

            if (value.IsNull || value == string.Empty)  //数据为空
            {
                if (!rule.EndsWith("?"))
                {
                    errMsg = string.Format("{0}数据为空", cellAddress);
                }
            }
            else  //验证数据类型
            {
                string typeError = "";
                rule = rule.ToLower().Trim(' ', '?');
                switch (rule.Trim())
                {
                    case "int":
                        {
                            typeError = value.IsInt ? "" : "{0}输入的整型格式不正确";
                        }
                        break;
                    case "float":
                        {
                            typeError = value.IsFloat ? "" : "{0}输入的数值格式不正确";
                        }
                        break;
                    case "datetime":
                        {
                            typeError = value.IsDateTime ? "" : "{0}输入的日期格式不正确";
                        }
                        break;
                }
                if (!string.IsNullOrEmpty(typeError))
                    errMsg = string.Format(typeError, cellAddress);
            }
            if (errMsg != string.Empty && !string.IsNullOrEmpty(errorMessage))
                errMsg = errorMessage;

            return errMsg;
        }
    }
}